package com.laobiao.file_netty_lib.packet;

import com.laobiao.file_netty_lib.exception.FileBaseException;
import com.laobiao.file_netty_lib.packet.command.PacketCommandType;
import com.laobiao.file_netty_lib.packet.command.ResoultCommand;
import com.laobiao.file_netty_lib.packet.command.Mkdir.MkdirCommand;
import com.laobiao.file_netty_lib.packet.command.download.ClientFileDownloadCommand;
import com.laobiao.file_netty_lib.packet.command.download.ServerFileDownloadResoutCommand;
import com.laobiao.file_netty_lib.packet.command.fileDelete.FileDeleteCommand;
import com.laobiao.file_netty_lib.packet.command.filelist.FileListCommand;
import com.laobiao.file_netty_lib.packet.command.upload.FileUploadCommand;
import com.laobiao.file_netty_lib.packet.data.BaseDataPacket;

/**
 * 构建包工具类
 * @author 38079
 *
 */
public class PacketUtil {
	
	/**
	 * 根据字节数组数据构建包
	 * @param bytes
	 * @return
	 */
	public static BasePacket buildPacket(byte[] bytes) {
		if(bytes==null || bytes.length!=1024) {
			throw new FileBaseException("数据包解析错误，数据长度错误:"+bytes.length, FileBaseException.ERR_PARAM_WRONG);
		}
		PacketType packetType = BasePacket.judgePacketType(bytes);
		if(packetType==PacketType.COMMAND) {
			return getCommandPacket(bytes);
		}else if(packetType==PacketType.DATA) {
			return getDataPacket(bytes);
		}else {
			throw new FileBaseException("数据包解析错误，不支持的数据包类型！", FileBaseException.ERR_PARAM_WRONG);
		}
	}
	
	/**
	 * 构建数据包
	 * @param bytes 网络传输的数据，最长1024
	 * @return
	 */
	private static BasePacket getDataPacket(byte[] bytes) {
		
		return new BaseDataPacket(bytes);
	}

	/**
	 * 构建命令包
	 * @param bytes 网络传输的数据，最长1024
	 * @return
	 */
	private static BasePacket getCommandPacket(byte[] bytes) {
		switch (PacketCommandType.instance(bytes[1])) {
		case UPLOAD:
			return new FileUploadCommand(bytes);
		case DOWNLOAD:
			return new ClientFileDownloadCommand(bytes);
		case DOWNLOAD_RESOULT:
			return new ServerFileDownloadResoutCommand(bytes);
		case RESOULT:
			return new ResoultCommand(bytes);
		case FILE_LIST:
			return new FileListCommand(bytes);
		case FILE_DELETE:
			return new FileDeleteCommand(bytes);
		case MKDIR:
			return new MkdirCommand(bytes);
		default:
			throw new FileBaseException("数据包解析错误，不支持的命令包类型:"+((int)bytes[1]), FileBaseException.ERR_PARAM_WRONG);
		}
	}
	
	
	
}
